<?php

namespace App\Http\Controllers\WorkOrder\Web;

use App\Enums\WorkOrder\OrderEnum;
use App\Http\Controllers\BaseController;
use App\Jobs\Export\Export;
use App\Service\WorkOrder\Mission\MissionEngineService;
use App\Service\WorkOrder\Permission\PermissionService;
use App\Service\WorkOrder\Reject\WorkOrderRejectService;
use App\Service\WorkOrder\Web\OrderListService;
use App\Service\WorkOrder\WorkOrderService;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Symfony\Component\HttpFoundation\BinaryFileResponse;

class WorkOrderController extends BaseController
{
    public function orderPanel(Request $request)
    {
        $userId = getRmsUserId();

        $data = (new OrderListService())->orderPanel($userId);

        return $this->success($data);
    }

    /**
     * @param Request $request
     * @return array|JsonResponse
     * @throws ContainerExceptionInterface
     * @throws GuzzleException
     * @throws NotFoundExceptionInterface
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
     * @throws \Maatwebsite\Excel\Exceptions\NoTypeDetectedException
     * @throws \OSS\Core\OssException
     */
    public function orderLists(Request $request)
    {
        $userId                  = getRmsUserId();
        $export                  = $request->get("export", "false");
        $data['shopIds']         = (string)$request->get('shopIds', '');
        $data['step']            = (int)$request->get('step');
        $data['nowDealUid']      = (int)$request->get('nowDealUid');
        $data['dealUid']         = (int)$request->get('dealUid');
        $data['workOrderNo']     = (string)$request->get('workOrderNo');
        $data['problemPid']      = (int)$request->get('problemPid');
        $data['pageSize']        = (int)$request->get('pageSize', 15);
        $data['pageNum']         = (int)$request->get('pageNum', 1);
        $data['priority']        = $request->get('priority');
        $data['sourceType']        = $request->get('sourceType', "");
        $data['tabType']         = (int)$request->get('tabType');
        $data['problemChildIds'] = (string)$request->get('problemChildIds');
        $data['submitTimeStart'] = (string)$request->get("submitTimeStart", "");
        $data['submitTimeEnd']   = (string)$request->get("submitTimeEnd", "");
        $data['updateTimeStart'] = (string)$request->get("updateTimeStart", "");
        $data['updateTimeEnd']   = (string)$request->get("updateTimeEnd", "");
        $data['shopSearch']      = (string)$request->get("shopSearch", "");
        $data['goodsName']       = (string)$request->get("goodsName", "");
        $data['shopPatter']      = (string)$request->get("shopPatter", '');
        // 权限
        $data['permission'] = (new PermissionService())->orderLists($userId);
        //导出异步处理
        if ($export == "true") {
            $fileNamePrefix = OrderEnum::PROBLEM_PID_TEXT[$data['problemPid']] ?? '-';
            $fileNamePrefix .= '-' . time();
            dispatch(
                (new Export(
                    $fileNamePrefix, Export::TYPE_WORK_ORDER, [
                        'data'      => $data,
                        'userId'    => $userId,
                        'export'    => $export,
                        'startTime' => $data['submitTimeStart'],
                        'endTime'   => $data['submitTimeEnd'],
                    ]
                ))
            )->onQueue(Export::QUEUE_NAME);
            return $this->success([]);
        }
        $data = (new OrderListService())->orderLists($data, $userId, $export);

        return $this->success($data);
    }

    public function grabOrder(Request $request, string $workOrderNo)
    {
        $userId = getRmsUserId();

        (new OrderListService())->grabOrder($workOrderNo, $userId);

        return $this->success();
    }

    public function transfer(Request $request)
    {
        $workOrderNo = $request->get('workOrderNo', '');
        $targetUid   = $request->get('targetUid', 0);

        $this->validate($request, [
            'workOrderNo' => 'required|string',
            'targetUid'   => 'required|integer',
        ]);

        $userId = getRmsUserId();

        (new MissionEngineService($workOrderNo))->transfer($userId, $targetUid);

        return $this->success();
    }

    /**
     * 工单驳回
     *
     * @param Request $request
     * @param string $workOrderNo
     * @return JsonResponse
     */
    public function reject(Request $request, string $workOrderNo): JsonResponse
    {
//        $content = [
//            [
//                'field'            => 'shopName',
//                'fieldText'        => '门店名称',
//                'reasonOptionText' => '其他',
//                'reasonText'       => '自定义的驳回理由',
//            ],
//        ];

        $this->validate($request, [
            'content.*.field'            => 'required|string',
            'content.*.fieldText'        => 'required|string',
            'content.*.reasonOptionText' => 'string',
            'content.*.reasonText'       => 'required|string',
        ]);

        $content = $request->get('content');

        $userId = getRmsUserId();

        (new WorkOrderRejectService($workOrderNo))->doReject($userId, $content);

        return $this->success();
    }

    /**
     * @return JsonResponse
     */
    public function type(): JsonResponse
    {
        return $this->success(WorkOrderService::type());
    }
}
